package top.yangbuyi.system.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.yangbuyi.system.common.AccessLimit;
import top.yangbuyi.system.common.ClientIPUtils;
import top.yangbuyi.system.common.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description:  杨不易网站 :www.yangbuyi.top
 * program:  yangbuyi-erp-2020
 * ClassName:  FangshuaInterceptor
 * create:  2020-07-11 16:48
 *
 * @author: yangbuyi
 * @since： JDK1.8
 * @FangshuaInterceptor:
 **/

@Component
public class FangshuaInterceptor extends HandlerInterceptorAdapter {
      
      @Autowired
      private RedisTemplate redisTemplate;
      
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //判断请求是否属于方法的请求
            if (handler instanceof HandlerMethod) {
                  HandlerMethod hm = (HandlerMethod) handler;
                  //获取方法中的注解,看是否有该注解
                  AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
                  if (accessLimit == null) {
                        return true;
                  }
                  int seconds = accessLimit.seconds();
                  int maxCount = accessLimit.maxCount();
                  boolean login = accessLimit.needLogin();
                  String key = "";
                  //如果需要登录
                  if (login) {
                        //获取登录的session进行判断
                        //这里假设用户是1,项目中是动态获取的userId
                        HttpServletRequest httpServletRequest = WebUtils.getHttpServletRequest();
                        key = ClientIPUtils.getClientIp(httpServletRequest);
                  }
                  //从redis中获取用户访问的次数
                  if (key == null) {
                        return true;
                  }
                  
                  Integer count = (Integer) redisTemplate.opsForValue().get(key);
                  System.out.println(count + "==============================" + key);
                  if (count == null) {
                        //第一次访问
                        redisTemplate.opsForValue().set(key, 1, seconds, TimeUnit.SECONDS);
                  } else if (count < maxCount) {
                        //加1
                        redisTemplate.opsForValue().increment(key, 1);
                  } else {
                        //超出访问次数
                        //这里的CodeMsg是一个返回参数
                        render(response, "超出访问次数");
                        return false;
                  }
            }
            return true;
      }
      
      /**
       * 这里是返回前端的信息
       *
       * @param response
       * @param cm
       * @throws Exception
       */
      private void render(HttpServletResponse response, String cm) throws Exception {
            System.out.println("进来啦");
            System.out.println("进来啦");
            System.out.println("进来啦");
//            response.setContentType("application/json;charset=UTF-8");
//            OutputStream out = response.getOutputStream();
//            String str = JSON.toJSONString(new ResultObj(200, cm));
//            out.write(str.getBytes("UTF-8"));
//            out.flush();
//            out.close();
            
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("code", -1);
            resultData.put("msg", "请求数据频繁，请稍后再试！！！！");
            PrintWriter out = response.getWriter();
            //使用fastjson的对象转化方法
            out.write(JSONObject.toJSON(resultData).toString());
            
            
      }
      
      
}
